<!-- 工作班次展示 -->

<template>

    <div id="parent">
        <div style="text-align: left;" :hidden="userType==='employee'">
            <div>
                <el-radio-group v-model="radio1" visbility=hidden>
                    <el-radio-button label="部门"></el-radio-button>
                    <el-radio-button label="个人"></el-radio-button>
                </el-radio-group>
                <template v-if="radio1==='部门' ">
                    <el-select v-model="value"  clearable placeholder="请选择部门" :disabled="userType==='department_manager'" style="width: 160px;color: #a667ff;padding-left:3%;">
                        <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
                        </el-option>
                    </el-select>
                </template>
                <template v-else-if="radio1==='个人'">
                    <el-input v-model="currentWorker.WorkerId" placeholder="请输入员工工号" style="width:160px;color: aqua;padding-left:3%;"></el-input>
                </template>
                <el-button type="primary" icon="el-icon-search" @click='confirm(currentWorker.WorkerId)'>确认</el-button>
                <el-button style="float: right;" type="primary" icon="el-icon-s-management" label-position="right"
                    @click="saveEdit()">保存</el-button>
            </div>
        </div>


        <template v-if="radio1==='个人' ||userType==='employee' ">
            <div class="header">
                <div class="left">
                    <el-button-group>
                        <el-button type="primary" size="mini" @click="prev">&lt;</el-button>
                        <el-button type="primary" size="mini" @click="next">&gt;</el-button>
                    </el-button-group>
                    &nbsp;&nbsp;&nbsp;{{headerContent}}
                </div>
                <div>
                    <span>{{currentWorker.WorkerName}}'s&nbsp;&nbsp;workshift</span>
                </div>
                <div class="right">
                    <el-button-group>
                        <el-button type="primary" size="mini" @click="switchMonth">月</el-button>
                        <el-button type="primary" size="mini" @click="switchWeek">周</el-button>
                    </el-button-group>
                </div>
            </div>
            
            <div class="body">
                <table class="month-table" cellspacing="0" cellpadding="0" v-show="showMonth">
                    <thead>
                        <th>Mon</th>
                        <th>Tue</th>
                        <th>Wed</th>
                        <th>Thu</th>
                        <th>Fri</th>
                        <th>Sat</th>
                        <th>Sun</th>
                    </thead>
                    <tbody>
                        <!-- 双重for循环生成 6 * 7 = 42 个日期格子 -->
                        <tr v-for="(week, weekIndex) in dates" v-bind:key="weekIndex">
                            <td v-for="(date, dateIndex) in dates[weekIndex]" v-bind:key="dateIndex" @mouseenter="dateMouseEnter(weekIndex, dateIndex)"
                                @mouseleave="dateMouseLeave(weekIndex, dateIndex)">
                                <div class="date" :class="[date.class, date.isAlive]">
                                    <template v-if="date.class!='not-current-month '">
                                        <el-popover placement="top-start" title="" width="200" trigger="click"
                                            :disabled="userType==='employee'" content="这是一段内容,这是一段内容,这是一段内容,这是一段内容。">
                                            <span slot="reference">{{date.day}}</span>
                                            <!-- <el-tag type="success">aaa</el-tag> -->
                                            <!--                                        <el-button @click="setWorkShiftInCalendar(date)">button</el-button>
 -->
                                            <h3>更改班次</h3>
                                            <el-select v-model="date.workingHours" placeholder="请选择">
                                                <el-option v-for="item in commonShift" :key="item.value" :label="item.label"
                                                    :value="item.value">
                                                </el-option>
                                            </el-select>
                                        </el-popover>
                                        <div>
                                            <template v-if="date.workingHours=== '7:00-15:00'">
                                                <el-tag type="success">{{ date.workingHours }}</el-tag>
                                            </template>
                                            <template v-else-if="date.workingHours=== '11:00-20:00'">
                                                <el-tag type="warning">{{ date.workingHours}}</el-tag>
                                            </template>
                                            <template v-else-if="date.workingHours=== '15:00-23:00'">
                                                <el-tag type="danger">{{date.workingHours}}</el-tag>
                                            </template>
                                            <template v-else-if="date.workingHours!= ''">
                                                <el-tag type="primary">{{date.workingHours}}</el-tag>
                                            </template>
                                        </div>
                                    </template>
                                    <template v-else-if="date.class==='not-current-month '">
                                        <span>{{date.day}}</span>
                                    </template>
                                </div>
                            </td>
                        </tr>
                    </tbody>
                </table>
                <!-- 生成一个周 时间列表 -->
                <table class="week-table" cellspacing="0" cellpadding="0" v-show="!showMonth">
                    <thead>
                        <th></th>
                        <th v-for="(header, index) in weekTableHeader" v-bind:key="index" :class="header.class">{{header.date}}</th>
                    </thead>
                    <tbody>
                        <tr v-for="(hourMinute, index) in weekList[0]" v-bind:key="index">
                            <td>
                                <div class="hours">
                                    <span>{{hourMinute}}</span>
                                </div>
                            </td>
                            <td :style="{'background-color':setColor(0,index)}"></td>
                            <td :style="{'background-color':setColor(1,index)}"></td>
                            <td :style="{'background-color':setColor(2,index)}"></td>
                            <td :style="{'background-color':setColor(3,index)}"></td>
                            <td :style="{'background-color':setColor(4,index)}"></td>
                            <td :style="{'background-color':setColor(5,index)}"></td>
                            <td :style="{'background-color':setColor(6,index)}"></td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </template>
        <template v-else-if=" radio1==='部门'">
            <workShiftShowMonth :department="value"  :monthSave="monthSave" :monthConfirm="monthConfirm" v-on:monthSave2false="monthSave2false"   
			v-on:monthConfirm2false="monthConfirm2false" @getCommonWork="getCommonWorkShift"></workShiftShowMonth>
            <!-- 		  <el-button>按钮</el-button>
 -->
        </template>
    </div>
</template>




<script>
    import moment from 'moment'
    import axios from "axios"
    import workShiftShowMonth from "./workShiftShowMonth.vue";
    // import JSON from "JSON"


    export default {
        data() {
            return {
                userType: this.$store.state.userType, //当前员工类型
                userName: this.$store.state.userName,
                today: moment().format('YYYY-MM-DD'),
                currentYearMonth: moment().format('YYYY-MM'),
                weekTableHeader: [],
                dates: [],
                daysDistance: '',
                showMonth: true,
				monthSave: false,
				monthConfirm:false,
                weekList: [],
                headerContent: moment().format('YYYY-MM'),
                currentWeekday: '',
                // workingHours: [],
                workingTimesUpdate: [],
                workingTimes: ['7:00-15:00', '15:00-23:00', '7:00-15:00', '11:00-20:00', '11:00-20:00', '7:00-15:00',
                    '15:00-23:00'
                ],
                options: [{
                    value: '1',
                    label: '技术部门'
                }, {
                    value: '2',
                    label: '管理部门'
                }, {
                    value: '3',
                    label: '财政部门'
                }, {
                    value: '4',
                    label: '销售部门'
                }, {
                    value: '5',
                    label: '后勤部门'
                }, ],
                value: '1',//currentWorker.userDepartmentId, //部门值
                radio1: '个人',
                commonShift: [{
                    value: '7-15',
                    label: '早班'
                }, {
                    value: '11-20',
                    label: '午班'
                }, {
                    value: '15-23',
                    label: '晚班'
                }, {
                    value: '',
                    label: '其他'
                }, ],
                currentWorker: {
                    WorkerId: '',
                    WorkerName: '',
					userDepartmentId:''
                },
				

            }
        },
        methods: {
            // 点击上个月 通过改变currentYearMonth来获取上个月的 YYYY-MM 格式

            prev() {
                if (this.showMonth) {
                    this.currentYearMonth = moment(this.currentYearMonth).subtract(1, 'months').format('YYYY-MM')
                    this.headerContent = this.currentYearMonth
                    this.getPersonalWorkShift()
                } else {
                    this.currentWeekday = moment(this.currentWeekday).subtract(7, 'days')
                    this.weekHeaderContent()
					this.createWeekList()
                    this.getPersonalWorkShift()
                }

            },
            next() {
                if (this.showMonth) {
                    this.currentYearMonth = moment(this.currentYearMonth).add(1, 'months').format('YYYY-MM')
                    this.headerContent = this.currentYearMonth
                    this.getPersonalWorkShift()
                } else {
                    this.currentWeekday = moment(this.currentWeekday).add(7, 'days')
                    this.weekHeaderContent()
					this.createWeekList()
                    this.getPersonalWorkShift()
                }
            },
            switchMonth() {
                this.showMonth = true
                this.headerContent = this.currentYearMonth
				this.getPersonalWorkShift(this.currentWorker.WorkerId)
            },
            switchWeek() {
                this.showMonth = false
                this.weekHeaderContent()
				this.getPersonalWorkShift(this.currentWorker.WorkerId)
            },
            dateMouseEnter(weekIndex, dateIndex) {
                this.dates[weekIndex][dateIndex].isAlive = 'date-alive'
            },
            dateMouseLeave(weekIndex, dateIndex) {
                this.dates[weekIndex][dateIndex].isAlive = ''
            },
            createCalendar() {
                this.dates = []
                // 获取当月的一号是星期几 以便来生成上月的日期 填补够42个格子
                const monthFirstDay = moment(this.currentYearMonth + '-01', 'YYYY-MM-DD')

                // // 获得一号与第一个格子内应该有的天数距离 这里需要注意的是 weekday 是从周日 为 0 开始的
                let firstDayWeekday = moment(monthFirstDay).weekday()
                if (firstDayWeekday === 0) {
                    firstDayWeekday = 7
                }
                let daysDistance = 1 - firstDayWeekday
                this.daysDistance = daysDistance
                for (let weeks = 0; weeks < 6; weeks++) {
                    this.dates.push([])
                    for (let weekday = 0; weekday < 7; weekday++) {
                        // 该对象有四个属性 一个是class属性 二是本日对应日期 三是本日工作点钟（班次） 四是早、午、晚/其他班属性 
                        let date = {}
                        date.day = moment(monthFirstDay).add(daysDistance, 'days')
                        // console.log(date.day)
                        date.workingHours = ''
                        date.workingStatus = ''
                        date.isAlive = ''
                        const dayMonth = moment(date.day).month()
                        // 是这个月的日期
                        if (dayMonth === moment(monthFirstDay).month()) {
                            date.class = 'current-month '
                            // console.log(date.day)
                            let tmp = Number(String(date.day).split(' ')[2])
                            if (this.workingTimes[tmp - 1] != '') {
                                date.workingHours = this.workingTimes[tmp - 1]
                            } else {
                                date.workingHours = ''
                            }
                            //starttime
                            // 日期是今天的高亮
                            if (moment(date.day).isSame(this.today, 'days')) {
                                date.class += 'today '
                            }
                        } else {
                            date.class = 'not-current-month '
                        }
                        date.day = moment(date.day).format('DD')
                        // console.log(date.day)
                        this.dates[weeks].push(date)

                        // date.info = "";
                        daysDistance++
                    }
                }

            },
            createWeekList() {
                this.weekTableHeader = ['Mon ', 'Tue ', 'Wed ', 'Thu ', 'Fri ', 'Sat ', 'Sun ']
                this.weekList = []
                for (let index = 0; index < 7; index++) {
                    let item = {}
                    item.date = moment(this.currentWeekday).add(index, 'days')
                    if (item.date.isSame(this.today, 'days')) {
                        item.class = 'today'
                    }
                    item.date = this.weekTableHeader[index] + item.date.format('MM/DD')
                    this.weekTableHeader[index] = item
                }
                for (let days = 0; days < 7; days++) {
                    this.weekList.push([])
                    // this.workingHours.push([])
                    let item = ''
                    for (let hours = 0; hours < 48; hours++) {
                        if (hours % 2 === 0) {
                            item = hours / 2 + '点'
                        } else {
                            item = ''
                        }
                        this.weekList[days].push(item)
                    }
                }
            },
            weekHeaderContent() {
                this.headerContent = moment(this.currentWeekday).format('MM/DD') + '~' + moment(this.currentWeekday).add(
                        6, 'days')
                    .format('MM/DD')
            },
            fun: function(data) {
                // console.log(data);
                data = data.split("-");
                return data[0] + ":00-" + data[1] + ":00";
            },
            save: function() {
                this.workingTimesUpdate = []
                let dis = this.daysDistance
                for (let i = 0; i < this.dates.length; i++) {
                    for (let j = 0; j < this.dates[i].length; j++) {
                        if (this.dates[i][j].class != 'not-current-month ') {
                            let item = ''
                            // item.date = moment(this.currentYearMonth).format('MM') + '-' + this.dates[i][j].day
                            if (this.dates[i][j].workingHours != '') {
                                item = this.dates[i][j].workingHours
                            }
                            // console.log(item.date)
                            this.workingTimesUpdate.push(item)
                        }
                    }
                }
                for (let i = 0; i < this.workingTimesUpdate.length; i++)
                    this.workingTimes[i] = this.workingTimesUpdate[i]
                console.log(this.workingTimes)
            },
            confirm(id) {
				
			if(this.radio1==='个人')
              this.getPersonalWorkShift(id)
			  else if(this.radio1==='部门'){
			this.monthConfirm=true
	
				  }
            },
            getPersonalWorkShift(id) {
                var _this = this
                let start_time = this.showMonth? moment(this.currentYearMonth + '-01', 'YYYY-MM-DD'):moment(this.currentWeekday,'YYYY-MM-DD') //.format('YYYY-MM-DD')
                let _start_time = start_time.format('YYYY-MM-DD')
                let end_time = this.showMonth?start_time.add(1, 'months').subtract(1, 'days') :moment(start_time).add(6,"days")//.format('YYYY-MM-DD')
                let _end_time = end_time.format('YYYY-MM-DD')
				let _id=this.$store.state.userId
				console.log(id===undefined)
				if(id!=undefined)
					_id=id
				console.log(_id)
                console.log("this is getPersonalWorkShift, http://127.0.0.1:8000/api/workshift/user/")
                axios.get("http://127.0.0.1:8000/api/workshift/user/", {
                        params: {
                            user_id: _id,
                            start_time: _start_time,
                            end_time: _end_time,
                        }
                    })
                    .then(function(response) {
                        console.log(response);
						if(response.data.status===1){
						_this.$message.error('请输入正确员工id');
						return
						} 
						else if(response.data.status===2){
						_this.$message.warning('您无权访问其他部门员工');
							return
							}
                        _this.workingTimes = []
                        let data = []
                        data = response.data.data
                        for (let i = 0; i < data.length; i++) {
                            _this.workingTimes[i] = data[i]
                        }
                        // console.log(_this.workingTimes);
                        _this.createCalendar()
						_this.currentWorker.WorkerName=response.data.user_name
						_this.currentWorker.WorkerId=_id
                    })
                    .catch(function(error) {
                        console.log(error);
                    })
            },
            saveEdit() {
				
				console.log(this.radio1)
				if (this.radio1 === "部门"){
					this.monthSave = true;
					return null;
				}
				
                this.save()
				console.log("this is:")
				console.log(this.workingTimes)
                var _this = this
                let start_time = moment(this.currentYearMonth + '-01', 'YYYY-MM-DD') //.format('YYYY-MM-DD')
                let _start_time = start_time.format('YYYY-MM-DD')
                let end_time = start_time.add(1, 'months').subtract(1, 'days') //.format('YYYY-MM-DD')
                let _end_time = end_time.format('YYYY-MM-DD')
                // console.log(_start_time)
                // console.log(_end_time)
                axios.post("http://127.0.0.1:8000/api/workshift/user/application/", JSON.stringify({
                        "name": _this.currentWorker.WorkerName,
                        "start_time":_start_time,
                        "end_time": _end_time,
                        "data": _this.workingTimes
                    }))
                    .then(function(response) {
                        console.log(response)
						_this.$message.success('保存成功');
                    })
                    .catch(function(error) {
                        console.log(error);
                    })
            },
            setColor(index0, index1) {
                let time = this.workingTimes[index0]
                if (time === ""){
                    return "";
                }
                
                let starttime = time.split('-')[0].split(':')[0]
				// console.log("starttime"+starttime)
				// console.log("time"+time)
                let endtime = time.split('-')[1].split(':')[0]
                if (time === '7:00-15:00' && starttime <= index1 / 2 && index1 / 2 < endtime)
                    return '#67C23A'
                else if (time === '11:00-20:00' && starttime <= index1 / 2 && index1 / 2 < endtime)
                    return '#E6A23C'
                else if (time === '15:00-23:00' && starttime <= index1 / 2 && index1 / 2 < endtime)
                    return '#F56C6C';
                else if (time != '' && starttime <= index1 / 2 && index1 / 2 < endtime)
                    return '#909399'
                else
                    return ''
            },
            getCommonWorkShift() {
                var _this = this
                axios.get("http://127.0.0.1:8000/api/WorkShiftItem/")
                    .then(function(response) {
                        // console.log(response);
                        let data = []
                        data = response.data.data
                        // console.log(data11)
                        let tmp = _this.commonShift.length
                        // console.log(_this.commonShift)
                        while (tmp > 3) {
                            _this.commonShift.pop()
                            tmp--
                        }
                        // console.log(_this.commonShift)
                        for (let i = 0; i < 3; i++) {
                            let update = data[i].start_time + '-' + data[i].end_time
                            if (_this.commonShift[i].value != update)
                                _this.commonShift[i].value = update
                        }
                        for (let i = 3; i < data.length; i++) {
                            let update = data[i].start_time + '-' + data[i].end_time
                            let item = {}
                            item.value = update
                            item.label = data[i].name
                            _this.commonShift.push(item)
                        }
						let item={}
						item.value=''
						item.label="空"
						_this.commonShift.push(item)
                    }).catch(function(error) {
                        console.log(error);
                    })

            },
            getDepartmentWorkShift() {
                var _this = this
                let start_time = moment(this.currentYearMonth + '-01', 'YYYY-MM-DD') //.format('YYYY-MM-DD')
                let _start_time = start_time.format('YYYY-MM-DD')
                let end_time = start_time.add(1, 'months').subtract(1, 'days') //.format('YYYY-MM-DD')
                let _end_time = end_time.format('YYYY-MM-DD')
                axios.get("http://127.0.0.1:8000/api/workshift/department/", {
                        params: {
                            department_id: '1',
                            start_time: '2020-06-01',
                            end_time: '2020-06-30'
                        }
                    })
                    .then(function(response) {
                        // console.log(response);

                        // _this.workingTimes=[]
                        // let data=[]
                        //  data=response.data.data
                        // for(let i=0;i<data.length;i++){
                        // _this.workingTimes[i]=data[i]
                        // }
                        // // console.log(_this.workingTimes);
                        // _this.createCalendar()
                    })
                    .catch(function(error) {
                        console.log(error);
                    })
            },
			monthSave2false:function(){
				console.log("this is month")
				this.monthSave = false;
			},
			monthConfirm2false:function(){
				console.log("this is confirm")
				this.monthConfirm = false;
			},
			getDepartment(){
				var _this = this;
				axios.get("http://127.0.0.1:8000/api/user/")
				    .then(function (response) {
				console.log(response)
				_this.currentWorker.userDepartmentId = response.data.data.user_department_id;
				console.log(_this.currentWorker.userDepartmentId)
				_this.value=_this.currentWorker.userDepartmentId
			}).catch(function (error) {
                console.log(error);
            })
		
        }
		},
        created() {
            // v-show是在创建后 保留dom 只是做切换的 不会v-if那样 销毁dom 所以只需要创建一次
			this.getDepartment()
            this.createCalendar()
            let weekday = moment().weekday() === 0 ? 7 : moment().weekday()
            let daysDistance = 1 - weekday
            this.currentWeekday = moment().add(daysDistance, 'days')
            this.createWeekList()
            this.getCommonWorkShift()
            this.getPersonalWorkShift()
            // this.getDepartmentWorkShift()
			
        },

        mounted: function() {
            var times = "2020-06-10-10-00";
            var times = times.split("-");
            // var month = time[1]
        },
        components: {
            workShiftShowMonth,
        }
    }
</script>


<style>
    /* lang="less" scoped */
    #parent {
        margin: 2rem auto;
        padding: 1rem;
        border: 1px solid #ebeef5;
    }

    .header {
        display: flex;
        justify-content: space-between;
        padding: 12px 12px;
        font-size: 18px;
        border-bottom: 1px solid #ebeef5;
    }

    .body {
        padding: 12px 20px 35px;
    }

    table {
        table-layout: fixed;
        width: 100%;
    }

    table thead th {
        padding: 10px 0;
        font-weight: 400;
    }

    tbody tr {
        display: table-row;
        vertical-align: inherit;
        border-color: inherit;
    }

    .month-table tbody td {
        vertical-align: inherit;
        border-right: 1px solid #ebeef5;
        border-bottom: 1px solid #ebeef5;
    }

    .month-table tbody tr:first-child td {
        border-top: 1px solid #ebeef5;
    }

    .month-table tr td:first-child {
        border-left: 1px solid #ebeef5;
    }

    .date {
        box-sizing: border-box;
        padding: 8px;
        height: 84px;
    }

    .not-current-month {
        color: #909399;
    }

    .current-month {
        color: #000000;
    }

    .today {
        color: #F44E50;
        background-color: #FFFF99;
    }

    .date-alive {
        background-color: rgb(252, 212, 215);
    }

    .week-table tbody tr td {
        border: 1px solid #ebeef5;
    }

    .hours {
        text-align: center;
        height: 24px;
    }

    .itIsIn {
        background-color: indianred;
    }

    .itIsNotIn {
        color: green;
    }
</style>
